package org.paybiz.core.payplatform.tenPay.service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.paybiz.constant.PayConstant;
import org.paybiz.core.payplatform.tenPay.constant.TenPayConstant;
import org.paybiz.core.payplatform.tenPay.util.AutoCheckOrderHandler;
import org.paybiz.core.payplatform.tenPay.util.PayRequestHandler;
import org.paybiz.core.payplatform.tenPay.util.TenpayUtil;
import org.paybiz.core.payplatform.yeePay.util.HttpClientUtil;
import org.paybiz.core.service.pay.PayService;
import org.paybiz.model.PayModel;
import org.paybiz.model.PayReqResultDO;
import org.paybiz.util.DynamicConfig;
import org.paybiz.util.PaySignUtil;
import org.springframework.stereotype.Service;

/**
 * Description:
 * @author  LiChunming
 * @version V1.0 
 * @createDateTime：2010-10-19 上午11:30:57 
 * @Company: MSD. 
 * @Copyright: Copyright (c) 2010
 */
@Service("tenPayService")
public class TenPayServiceImpl implements PayService{

	// 日志对象
	private static final Log logger = LogFactory.getLog(TenPayServiceImpl.class);
	// 内部密钥
	private static String msdValue = "";
	// 商户编号
	private static String ten_MerId = "";
	// 商户密钥
	private static String ten_keyValue = "";
	// 支付回调链接
	private static String ten_returnUrl = "";
	// 支付查询链接
	private static String ten_queryUrl = "";
	
	public TenPayServiceImpl() {
		// 通过资源文件获取
		msdValue = DynamicConfig.getInstance().getValue(PayConstant.PAY_BIZ_KEY);
		ten_MerId = DynamicConfig.getInstance().getValue(TenPayConstant.TEN_MERID);
		ten_keyValue = DynamicConfig.getInstance().getValue(TenPayConstant.TEN_KEYVALUE);
		ten_returnUrl = DynamicConfig.getInstance().getValue(
		        TenPayConstant.TEN_RETURNURL);
		ten_queryUrl = DynamicConfig.getInstance().getValue(TenPayConstant.TEN_QUERYURL);
	}
	@Override
	public PayReqResultDO pay(PayModel payDO) {
		PayReqResultDO reqResultDO=new PayReqResultDO();
    	//创建PayRequestHandler实例
    	PayRequestHandler reqHandler = new PayRequestHandler();
    	//设置密钥
    	reqHandler.setKey(ten_keyValue);

    	//初始化
    	reqHandler.init();

    	//-----------------------------
    	//设置支付参数
    	//-----------------------------
    	reqHandler.setParameter("bargainor_id", ten_MerId);			                                   //商户号
    	reqHandler.setParameter("sp_billno", payDO.getOrderId());		                               //商家订单号
    	reqHandler.setParameter("transaction_id", ten_MerId+payDO.getOrderId());		               //财付通交易单号=商户号+商家订单号
    	reqHandler.setParameter("return_url",StringUtils.isNotEmpty(payDO.getSynCallbackUrl()) 
    	        ? payDO.getSynCallbackUrl() : ten_returnUrl);			                               //支付通知url
    	reqHandler.setParameter("desc", payDO.getBody());	                                   //商品名称
    	reqHandler.setParameter("total_fee",payDO.getPayMoney().toString());	                       //总金额，以分为单位,不允许包含任何字符
    	reqHandler.setParameter("attach",payDO.getResultUrl());                                        //商家数据包(自己定义)，原样返回。
    	//商品金额,以分为单位
    	//用户ip,测试环境时不要加这个ip参数，正式环境再加此参数
    	reqHandler.setParameter("spbill_create_ip",payDO.getUserRequestIp());
    	String requestUrl = "";
    	try {
    		requestUrl=  reqHandler.getRequestURL();
    		
    		reqResultDO.setPayUrl(requestUrl);
    		reqResultDO.setResult(0);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			reqResultDO.setResult(1);
			reqResultDO.setErrMsg(e.getMessage());
		}                                                                //获取请求带参数的url
		reqResultDO.setHmac(PaySignUtil.getPayReqResultDOHmac(reqResultDO, msdValue));
		return reqResultDO;
	}

	/**
	 * return -1 未支付   0  支付失败   1 支付成功  2异常情况 
	 */
	@Override
	public int autoCheckOrder(String orderId,Date date,Integer tag) {
		int isSuccess = -1;//未支付
		//创建AutoCheckOrderHandler实例
    	AutoCheckOrderHandler autoCheckOrderHandler = new AutoCheckOrderHandler();
    	autoCheckOrderHandler.setGateUrl(ten_queryUrl);
    	//设置密钥
    	autoCheckOrderHandler.setKey(ten_keyValue);
    	//设置编码
    	autoCheckOrderHandler.setChartset("GB2312");
    	//-----------------------------
    	//设置查询参数
    	//--------------------------
    	autoCheckOrderHandler.setParameter("cmdno", "2");
    	autoCheckOrderHandler.setParameter("bargainor_id", ten_MerId);			                                   //商户号
    	autoCheckOrderHandler.setParameter("sp_billno", orderId);		                               //商家订单号
    	autoCheckOrderHandler.setParameter("transaction_id", ten_MerId+orderId);		               //财付通交易单号=商户号+商家订单号
    	autoCheckOrderHandler.setParameter("date", TenpayUtil.formatDate(date));
    	autoCheckOrderHandler.setParameter("attach", "1");
    	autoCheckOrderHandler.setParameter("charset", autoCheckOrderHandler.getChartset());
    	autoCheckOrderHandler.setParameter("output_xml", "1");
    	//设置商户订单日期
		String queryUrl = "";
    	try {
			queryUrl = autoCheckOrderHandler.getRequestURL();
			if(logger.isInfoEnabled()){
				logger.info("财付请求链接:"+queryUrl);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if(logger.isInfoEnabled()){
			logger.info("财付通查询参数:"+autoCheckOrderHandler.getDebugInfo());
		}
		String xmlString = HttpClientUtil.getResponseByGet(queryUrl, null);
		if(logger.isDebugEnabled()){
			logger.debug("收到的结果xml字符串：\n"+xmlString);
		}
		String result = "";
		String charset = "GB2312";
		String sign = "";
		SortedMap<String, String> resultParam = new TreeMap<String, String>();
		 //解析XML
        logger.info("解析XML：\n");
        try {
			if(xmlString!=null && !xmlString.trim().equals("")){
				Document document = DocumentHelper.parseText(xmlString);
				Element responseData = document.getRootElement();
				for (Iterator i = responseData.elementIterator(); i.hasNext();) {
					Element element = (Element) i.next();
					if(logger.isDebugEnabled()){
						logger.debug(element.getName() + ":" + element.getText());
					}
					if("attach".equals(element.getName())){
						resultParam.put("attach", element.getText());
					}else if("bargainor_id".equals(element.getName())){
						resultParam.put("bargainor_id", element.getText());
					}else if("charset".equals(element.getName())){
						charset = element.getText();
					}else if("cmdno".equals(element.getName())){
						resultParam.put("cmdno", element.getText());
					}else if("date".equals(element.getName())){
						resultParam.put("date", element.getText());
					}else if("fee_type".equals(element.getName())){
						resultParam.put("fee_type", element.getText());
					}else if("pay_info".equals(element.getName())){
						resultParam.put("pay_info", element.getText());
					}else if("pay_result".equals(element.getName())){
						result = element.getText();
						resultParam.put("pay_result", element.getText());
					}else if("sign".equals(element.getName())){
						sign = element.getText();
						if(logger.isInfoEnabled()){
							logger.info("财付通返回的签名sign: " + sign);
						}
					}else if("sp_billno".equals(element.getName())){
						resultParam.put("sp_billno", element.getText());
					}else if("total_fee".equals(element.getName())){
						resultParam.put("total_fee", element.getText());
					}else if("transaction_id".equals(element.getName())){
						resultParam.put("transaction_id", element.getText());
					}
				}
			}else{
				if(logger.isInfoEnabled()){
					logger.info("财付通查询返回xml为空");
				}
				//查询异常
				return 2;
			}
			if(logger.isInfoEnabled()){
				logger.info("财付通查询返回参数: [" + resultParam + "]");
			}
			String newSign = TenpayUtil.createSign(resultParam, ten_keyValue, charset);
			if("".equals(newSign) || !newSign.equals(sign.toLowerCase())){
				if(logger.isInfoEnabled()){
					logger.info("财付通查询签名失败,财付通签名:" + sign +"本地签名:" + newSign);
				}
				if("".equals(result) || !"0".equals(result)){
					logger.info("财付通支付交易单不存在");
					return -1;
				}
				//查询异常
				return 2;
			}
			if(!"".equals(result) && "0".equals(result)){
				isSuccess = 1;//支付成功
				if (logger.isInfoEnabled()) {
					logger.info("自动对账订单ID:"+orderId+" 财付通已支付成功!");
				}
			}
		} catch (Exception e) {
			if(logger.isInfoEnabled()){
				logger.info("财付通查询返回时解析xml出错,原因："+e.getMessage());
			}
			e.printStackTrace();
			//查询异常
			return 2;
		}
    	return isSuccess;
	}
	
	

	
}
